package com.example.teachmvandroidchart.ui

import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.AdapterView
import android_serialport_api.SerialPortFinder
import androidx.fragment.app.FragmentActivity
import com.android.frame.mvp.CommonBaseActivity
import com.bjw.bean.ComBean
import com.bjw.utils.SerialHelper
import com.example.databasetest.MyDatabaseHelper
import com.example.teachmvandroidchart.Adapter.SpAdapter
import com.example.teachmvandroidchart.databinding.ActivityHomeBinding
import com.example.teachmvandroidchart.databinding.ActivityHomesBinding
import com.example.teachmvandroidchart.util.ByteUtil
import com.example.teachmvandroidchart.widget.DynamicLineChartManager
import com.gyf.immersionbar.ImmersionBar
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*

/**
 * Created by dell on 2021/8/11.
 */
class SeriaPortHomesActivity: CommonBaseActivity<ActivityHomesBinding>() {
    //串口
    private var serialPortFinder: SerialPortFinder? = null
    private var serialHelper: SerialHelper? = null
    //曲线
    private var dynamicLineChartManager1: DynamicLineChartManager? = null
    private var dynamicLineChartManager2: DynamicLineChartManager? = null
    private var dynamicLineChartManager3: DynamicLineChartManager? = null
    private var dynamicLineChartManager4: DynamicLineChartManager? = null
    //房间数据集
    private val list: MutableList<Float> = ArrayList() //数据集合
    private val list2: MutableList<Float> = ArrayList() //数据集合
    private val list3: MutableList<Float> = ArrayList() //数据集合
    private val list4: MutableList<Float> = ArrayList() //数据集合

    private val names: MutableList<String> = ArrayList() //折线名字集合
    private val colour: MutableList<Int> = ArrayList() //折线颜色集合
    //数据库
    private var dbHelper: MyDatabaseHelper? = null
    private val mHandler = Handler()
    override fun handleView(savedInstanceState: Bundle?) {
        intView()
        dbHelper = MyDatabaseHelper(this, "temperature.db", null, 1)
        Handler(Looper.getMainLooper()).postDelayed({
            /**
             * 数据初始化（200毫秒）AddDeviceActivity
             * */
            intChart()
            openSerialPort()
        }, 300)


    }
    private fun intView() {
        ImmersionBar.with(this).titleBar(binding.toolbar).keyboardEnable(true).init()
        ImmersionBar.with(this).titleBar(binding.toolbar).init()
        setSupportActionBar(binding.toolbar)
        val actionBar = supportActionBar
        actionBar?.setDisplayHomeAsUpEnabled(true)
        //设置文本不可输入
        binding.EditText1.isEnabled = false
        binding.EditText2.isEnabled = false
    }

    override fun initListener() {
        //打开串口
        binding.open.setOnClickListener{
            try {
                //将线程销毁掉
                mHandler.removeCallbacks(mRunnable)
                serialHelper?.open()
                //设置模拟数据可以被点击
                binding.SimulateData.isEnabled = true
                binding.open.text = "打开成功"
                showToast("打开成功")
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
        //添加数据
        binding.addEntry.setOnClickListener {
            dynamicLineChartManager1?.addEntry((Math.random() * 100).toFloat())
        }
        //模拟数据（simulated data）
        binding.SimulateData.setOnClickListener{
            //启动线程
            mHandler.post(mRunnable);
            //设置模拟数据不能被点击
            binding.SimulateData.isEnabled = false
        }
        //toolbar返回按钮监听
        binding.toolbar.setNavigationOnClickListener { finish() }
    }
    private fun intChart(){
        //折线名字
        names.add("温度")
        names.add("压强")
        //names.add("其他")
        //折线颜色
        colour.add(Color.CYAN)
        colour.add(Color.GREEN)
        //colour.add(Color.BLUE)

        dynamicLineChartManager1 = DynamicLineChartManager(binding.dynamicChart1, names, colour)
        dynamicLineChartManager1!!.setDescription("Home1")
        dynamicLineChartManager2 = DynamicLineChartManager(binding.dynamicChart2, names, colour)
        dynamicLineChartManager2!!.setDescription("Home2")
        dynamicLineChartManager3 = DynamicLineChartManager(binding.dynamicChart3, names, colour)
        dynamicLineChartManager3!!.setDescription("Home3")
        dynamicLineChartManager4 = DynamicLineChartManager(binding.dynamicChart4, names, colour)
        dynamicLineChartManager4!!.setDescription("Home4")
    }
    /*
    * TODO 串口使用初始化
    * */
    private fun openSerialPort(){
        serialPortFinder = SerialPortFinder()
        serialHelper = object : SerialHelper() {
            override fun onDataReceived(comBean: ComBean) {
                runOnUiThread {
                    /*
                    * TODO 获取串口数据已经保存数据
                    *  */
                    val formatter = SimpleDateFormat("yyyy-MM-dd")
                    val date: String = formatter.format(Date())
                    /*
                    * HH-mm-ss(24时制)
                    * hh-mm-ss(12时制)
                    * */
                    val formatte = SimpleDateFormat("HH:mm:ss")
                    val time = formatte.format(Date())

                    val db: SQLiteDatabase = dbHelper!!.writableDatabase

                    val home =
                        ByteUtil.hexStringToString(ByteUtil.bytesToHexString(comBean.bRec)).toString().substring(0, 2)
                    val tem =
                        ByteUtil.hexStringToString(ByteUtil.bytesToHexString(comBean.bRec)).toString().substring(5, 9)
                    val hum =
                        ByteUtil.hexStringToString(ByteUtil.bytesToHexString(comBean.bRec)).toString().substring(12, 16)

                    when(home.toInt()) {
                        1 -> {
                            val values = ContentValues()
                            //保存到数据库中
                            values.put("Home",home.toInt())
                            values.put("Date", date)
                            values.put("time", time)
                            values.put("temperatures", tem)
                            values.put("hum", hum)
                            db.insert("temp", null, values) // 插入第一条数据
                            values.clear()
                            //更新列表
                            list.add(tem.toFloat())
                            list.add(hum.toFloat())
                            dynamicLineChartManager1!!.addEntry(list)
                            list.clear()
                        }
                        2 -> {
                            val values = ContentValues()
                            //保存到数据库中
                            values.put("Home",home.toInt())
                            values.put("Date", date)
                            values.put("time", time)
                            values.put("temperatures", tem)
                            values.put("hum", hum)
                            db.insert("temp", null, values) // 插入第一条数据
                            values.clear()

                            list2.add(tem.toFloat())
                            list2.add(hum.toFloat())
                            dynamicLineChartManager2!!.addEntry(list2)
                            list2.clear()
                        }
                        3 -> {
                            val values = ContentValues()
                            //保存到数据库中
                            values.put("Home",home.toInt())
                            values.put("Date", date)
                            values.put("time", time)
                            values.put("temperatures", tem)
                            values.put("hum", hum)
                            db.insert("temp", null, values) // 插入第一条数据
                            values.clear()

                            list3.add(tem.toFloat())
                            list3.add(hum.toFloat())
                            dynamicLineChartManager3!!.addEntry(list3)
                            list3.clear()
                        }
                        4 -> {
                            val values = ContentValues()
                            //保存到数据库中
                            values.put("Home",home.toInt())
                            values.put("Date", date)
                            values.put("time", time)
                            values.put("temperatures", tem)
                            values.put("hum", hum)
                            db.insert("temp", null, values) // 插入第一条数据
                            values.clear()

                            list4.add(tem.toFloat())
                            list4.add(hum.toFloat())
                            dynamicLineChartManager4!!.addEntry(list4)
                            list4.clear()
                        }
                        else -> {
                        }
                    }

                }
            }
        }
        //获取串口地址
        val ports = serialPortFinder!!.allDevicesPath
        //设置波特率地址
        val botes = arrayOf(
            "0",
            "50",
            "75",
            "110",
            "134",
            "150",
            "200",
            "300",
            "600",
            "1200",
            "1800",
            "2400",
            "4800",
            "9600",
            "19200",
            "38400",
            "57600",
            "115200",
            "230400",
            "460800",
            "500000",
            "576000",
            "921600",
            "1000000",
            "1152000",
            "1500000",
            "2000000",
            "2500000",
            "3000000",
            "3500000",
            "4000000"
        )
        val spAdapter = SpAdapter(this)
        /*
         * TODO 适配下拉列表（串口地址）
        * */
        spAdapter.setDatas(ports)
        binding.spSerial.adapter = spAdapter
        binding.spSerial.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View,
                position: Int,
                id: Long
            ) {
                serialHelper?.close()
                serialHelper?.port = ports[position]
                binding.EditText1.setText(ports[position])
                binding.open.text = "关闭串口"
                //btOpen.setEnabled(true)
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
        /*
         * TODO 适配下拉列表（波特率地址）
        * */
        val spAdapter2 = SpAdapter(this)
        spAdapter2.setDatas(botes)
        binding.spBote.adapter = spAdapter2

        binding.spBote.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(
                parent: AdapterView<*>?,
                view: View,
                position: Int,
                id: Long
            ) {
                serialHelper?.close()
                serialHelper?.setBaudRate(botes[position])
                binding.EditText2.setText(botes[position])
                binding.open.text = "关闭串口"
                // btOpen.setEnabled(true)
            }

            override fun onNothingSelected(parent: AdapterView<*>?) {}
        }
    }
    /*
    * TODO 线程更新处理
    * */
    private val mRunnable: Runnable = object : Runnable {
        override fun run() {
            dynamicLineChartManager1?.addEntry((Math.random() * 100).toFloat())
            dynamicLineChartManager2?.addEntry((Math.random() * 100).toFloat())
            dynamicLineChartManager3?.addEntry((Math.random() * 100).toFloat())
            dynamicLineChartManager4?.addEntry((Math.random() * 100).toFloat())
            // 每3秒执行一次
            mHandler.postDelayed(this, 3000) //给自己发送消息，自运行
        }
    }

    override fun onDestroy() {
        //将线程销毁掉
        mHandler.removeCallbacks(mRunnable)
        super.onDestroy()
        serialHelper!!.close()
    }
}
